<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_User extends ORM {

	/**
	 * Complete the login for a user by incrementing the logins and saving login timestamp
	 *
	 * @return void
	 */
	public function complete_login()
	{
		if ($this->_loaded) {
			// Update the number of logins
			$this->logins = new Database_Expression('logins + 1');

			// Set the last login date
			$this->last_login = time();

			// Save the user
			$this->update();
		}
	}
    
    /**
     * Добавление пользователя
     * 
     * @param   string   email
     * @param   string   password
     * @return  Model_User
     */
    public function add_user($email, $password, $nick = null)
    {
        $email = trim($email);
        if (!$email) {
            throw new Model_Exception('E-mail должен быть задан');
        }
        if (!Valid::email($email)) {
            //throw new Model_Exception('E-mail некорректного формата'); 
        }
        
        $password = trim($password);
        if (!$password) {
            throw new Model_Exception('Пароль должен быть задан');
        }
        
        $this->email    = $email;
        if ($nick) {
            $this->nick = strip_tags($nick);
        }
        $this->password = Model_Auth::instance()->hash_password($password);
        $this->save();
        
        return $this;
    }
    
    /**
    * put your comment there...
    * 
    * @param mixed $email
    * @param mixed $password
    */
    public function edit_user($email, $password = null)
    {
        $this->email    = $email;
        if ($password) {
            $this->password = Model_Auth::instance()->hash_password($password);
        }   
        $this->save();
        
        return $this;
    }
    
    /**
     * put your comment there...
     * 
     */
    public function update_user()
    {
        
    }
    
    /**
     * put your comment there...
     * 
     */
    public function add_to_shop(Model_Shop $shop)
    {
        // TODO validation
        
        // Может он уже есть в магазине
        
        $user_shop = ORM::factory('User_Shop');  
        $user_shop->user_id = $this->id;
        $user_shop->shop_id = $shop->id; 
        $user_shop->role    = Model_User_Shop::ROLE_ADMINISTRATOR; 
        $user_shop->save();    
    }
    
    /**
     * put your comment there...
     * 
     */
    public function in_shop(Model_Shop $shop, $role = null)
    {
        $user_shop = ORM::factory('User_Shop')
                            ->where('user_id', '=', $this->id)
                            ->and_where('shop_id', '=', $shop->id)
                            ->find();

        if ($user_shop->loaded()) {
            if (!$role) {
                return true;
            }
            
            if ($role == $user_shop->role) {
                return true;
            }
        } 
        
        return false; 
    }
    
    public static function generate_password($length = 10)
    {
        $arr = array('a','b','c','d','e','f',
                 'g','h','i','j','k','l',
                 'm','n','o','p','r','s',
                 't','u','v','x','y','z',
                 'A','B','C','D','E','F',
                 'G','H','I','J','K','L',
                 'M','N','O','P','R','S',
                 'T','U','V','X','Y','Z',
                 '1','2','3','4','5','6',
                 '7','8','9','0',
                 '(',')','[',']',);
                 
        // Генерируем пароль
        $pass = '';
        for ($i = 0; $i < $length; $i++) {
            // Вычисляем случайный индекс массива
            $index = rand(0, count($arr) - 1);
            $pass .= $arr[$index];
        }
        return $pass;
    }

	/**
	 * Password validation for plain passwords.
	 *
	 * @param array $values
	 * @return Validation
	 */
	/*public static function get_password_validation($values)
	{
		return Validation::factory($values)
			->rule('password', 'min_length', array(':value', 8))
			->rule('password_confirm', 'matches', array(':validation', ':field', 'password'));
	}  */

}